package com.school.chapter01.homework;
@SuppressWarnings({"all"})

public class StudentsDuLinkList<T> {
    public static void main(String[] args) {
        StudentsDuLinkList<String> stu1 = new StudentsDuLinkList<>("1", "泽连斯基", "45", "123");

    }

    class Node {
        private T id;
        private T name;
        private T age;
        private T tel;
        private Node prev;
        private Node next;

        public Node() {
        }

        public Node(T id, T name, T age, T tel, Node prev, Node next) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.tel = tel;
            this.prev = prev;
            this.next = next;
        }
    }

    private Node header;
    private Node tail;
    private int size;

    public StudentsDuLinkList(T id, T name, T age, T tel) {
        Node node = new Node(id, name, age, tel, null, null);
        header = node;
        tail = header;
        size++;
    }

    //add方法实现在链表尾添加
    public void add(T id, T name, T age, T tel) {
        if (header == null) {
            header = new Node(id, name, age, tel, null, null);
            tail = header;
        } else {
            Node newNode = new Node(id, name, age, tel, tail, null);
            tail.next = newNode;
            tail = newNode;
        }
        size++;
    }

    public Node getNodeByIndex(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("线性表索引越界");
        }
        if (index <= size / 2) { // 从header节点开始搜索
            Node current = header;
            for (int i = 0; i < index; i++) {
                current = current.next;
            }
            return current;
        } else { // 从tail节点开始搜索
            Node current = tail;
            for (int i = size; i > index; i--) {
                current = current.prev;
            }
            return current;
        }
    }
    //deleteByIndex方法实现通过索引删除元素
    public void deleteByIndex(int index){
        if (index < size || index > size){
            throw new IndexOutOfBoundsException("非法索引");
        }
        Node del = null;
        if (0 == index) {
            del = header;
            header = del.next;
            del.next = null;
            header.prev = null;
        }else {
            //用prev表示要删除的元素的前一项
            Node prev = getNodeByIndex(index - 1);
            del = prev.next;
            prev.next = del.next;
            if (del.next != null) {
                del.next.prev = prev;
            }
            del.next = null;
            del.prev = null;
        }
        size--;
    }

    @Override
    public String toString() {
        return "StudentsDuLinkList{" +
                "header=" + header +
                ", tail=" + tail +
                ", size=" + size +
                '}';
    }
}
